<template>
  <div class="mycart-container">
    <h2>我的购物车</h2>

    <!-- 购物车列表 -->
    <el-table
        :data="cartData"
        border
        stripe
        style="width: 100%; margin-top: 15px;"
        v-loading="loading"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column prop="id" label="ID" width="80" align="center" />
      <el-table-column label="商品" width="200" align="center">
        <template #default="scope">
          <div class="product-info">
            <img
                :src="products.find(p => p.id === scope.row.product_id)?.img || defaultImg"
                alt="商品图片"
                class="product-img"
            >
            <span>{{ products.find(p => p.id === scope.row.product_id)?.name || '未知商品' }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="单价" width="100" align="center">
        <template #default="scope">
          {{ products.find(p => p.id === scope.row.product_id)?.price || 0 }}
        </template>
      </el-table-column>
      <el-table-column label="数量" width="180" align="center">
        <template #default="scope">
          <el-input-number
              v-model="scope.row.nums"
              :min="1"
              :max="products.find(p => p.id === scope.row.product_id)?.nums || 999"
              @change="handleNumChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="小计" width="100" align="center">
        <template #default="scope">
          {{ (scope.row.nums * (products.find(p => p.id === scope.row.product_id)?.price || 0)).toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column label="删除" width="100" align="center">
        <template #default="scope">
          <el-button
              type="danger"
              size="small"
              @click="handleDelete(scope.row)"
          >
            <i class="el-icon-delete"></i>
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 结算区域 -->
    <div class="checkout-area">
      <div class="total-info">
        <span>已选 {{ selectedCount }} 件商品，合计：¥ {{ totalAmount.toFixed(2) }}</span>
      </div>
      <el-button
          type="primary"
          size="large"
          @click="handleCheckout"
          :disabled="selectedCount === 0"
      >
        结算选中商品
      </el-button>
    </div>

    <!-- 结算弹窗（带表单验证） -->
    <el-dialog v-model="checkoutVisible" title="结算商品" width="500">
      <el-form
          :model="checkoutForm"
          label-width="120px"
          :rules="checkoutRules"
          ref="checkoutFormRef"
      >
        <el-form-item label="收件人" prop="receiver">
          <el-input v-model="checkoutForm.receiver" placeholder="请输入收件人" />
        </el-form-item>

        <el-form-item label="收货地址" prop="shipping_address">
          <el-input v-model="checkoutForm.shipping_address" type="textarea" rows="3" placeholder="请输入收货地址" />
        </el-form-item>

        <el-form-item label="联系电话" prop="receiver_phone">
          <el-input v-model="checkoutForm.receiver_phone" placeholder="请输入联系电话" />
        </el-form-item>

        <el-form-item label="商品总数">
          <el-input :value="selectedCount" disabled />
        </el-form-item>

        <el-form-item label="合计金额">
          <el-input :value="totalAmount.toFixed(2)" disabled />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="checkoutVisible = false">取消</el-button>
          <el-button type="primary" @click="submitCheckout">
            提交订单
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, inject, computed } from "vue";
import { ElMessage, ElMessageBox } from 'element-plus';
import buycarAPI from '../api/buycar_api.js';
import productAPI from '../api/product_api.js';
import orderAPI from '../api/order_api.js';
import lodash from 'lodash';

// 从全局获取登录用户信息
const loginAdmin = inject('loginAdmin');

// 表格数据
const cartData = ref([]);
const products = ref([]);
const loading = ref(false);
const defaultImg = 'https://xrysitu.oss-cn-beijing.aliyuncs.com/a2b619ac-9909-4af9-b75b-5e0fee3b7473.jpg';

// 选中的商品
const selectedProducts = ref([]);
const selectedCount = computed(() => {
  return selectedProducts.value.reduce((sum, item) => sum + item.nums, 0);
});

// 合计金额
const totalAmount = computed(() => {
  return selectedProducts.value.reduce((sum, item) => {
    const product = products.value.find(p => p.id === item.product_id);
    return sum + (item.nums * (product?.price || 0));
  }, 0);
});

// 结算弹窗相关
const checkoutVisible = ref(false);
const checkoutForm = ref({
  receiver: '',
  shipping_address: '',
  receiver_phone: ''
});

// 表单验证相关
const checkoutFormRef = ref(null);
const checkoutRules = ref({
  receiver: [
    { required: true, message: '请输入收件人', trigger: 'blur' }
  ],
  shipping_address: [
    { required: true, message: '请输入收货地址', trigger: 'blur' }
  ],
  receiver_phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码格式', trigger: 'blur' }
  ]
});

// 页面加载时初始化数据
onMounted(async () => {
  if (!loginAdmin.value.id) {
    ElMessageBox.alert('请先登录', '提示', { type: 'warning' });
    return;
  }
  await Promise.all([loadCartData(), loadProducts()]);
});

// 加载购物车数据
const loadCartData = async () => {
  loading.value = true;
  try {
    const result = await buycarAPI.page({
      user_id: loginAdmin.value.id,
      current: 1,
      limit: 100
    });
    cartData.value = result.data || [];
  } catch (error) {
    console.error('获取购物车数据失败:', error);
    ElMessage.error('获取购物车数据失败');
  } finally {
    loading.value = false;
  }
};

// 加载商品数据
const loadProducts = async () => {
  try {
    const result = await productAPI.page({ current: 1, limit: 100 });
    products.value = result.data || [];
  } catch (error) {
    console.error('获取商品数据失败:', error);
    ElMessage.error('获取商品数据失败');
  }
};

// 数量修改
const handleNumChange = async (row) => {
  try {
    await buycarAPI.edit({
      id: row.id,
      user_id: loginAdmin.value.id,
      product_id: row.product_id,
      nums: row.nums
    });
    ElMessage.success('数量已更新');
  } catch (error) {
    console.error('更新数量失败:', error);
    ElMessage.error('更新数量失败');
    // 失败时回滚
    await loadCartData();
  }
};

// 删除购物车项
const handleDelete = async (row) => {
  ElMessageBox.confirm(
      `确定要删除该商品吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(async () => {
    try {
      await buycarAPI.del(row.id);
      ElMessage.success('删除成功');
      await loadCartData();
    } catch (error) {
      ElMessage.error('删除失败');
      console.error(error);
    }
  }).catch(() => {
    // 取消删除
  });
};

// 选择商品变化
const handleSelectionChange = (selection) => {
  selectedProducts.value = selection;
};

// 打开结算弹窗
const handleCheckout = () => {
  if (selectedProducts.value.length === 0) {
    return ElMessage.warning('请选择要结算的商品');
  }

  // 初始化表单
  checkoutForm.value = {
    receiver: loginAdmin.value.name || '',
    shipping_address: '',
    receiver_phone: loginAdmin.value.phone || ''
  };

  checkoutVisible.value = true;
};

// 提交结算
const submitCheckout = async () => {
  // 表单验证
  if (!checkoutFormRef.value) return;

  try {
    await checkoutFormRef.value.validate();

    // 验证通过后执行订单提交逻辑
    // 1. 检查库存
    for (const item of selectedProducts.value) {
      const product = await productAPI.get(item.product_id);
      if (product.nums < item.nums) {
        const productName = products.value.find(p => p.id === item.product_id)?.name || '未知商品';
        return ElMessageBox.alert(`${productName}库存不足`, '提示', { type: 'warning' });
      }
    }

    // 2. 批量创建订单
    for (const item of selectedProducts.value) {
      const product = products.value.find(p => p.id === item.product_id);

      // 创建订单
      const order = {
        product_id: item.product_id,
        user_id: loginAdmin.value.id,
        receiver: checkoutForm.value.receiver,
        shipping_address: checkoutForm.value.shipping_address,
        receiver_phone: checkoutForm.value.receiver_phone,
        nums: item.nums,
        total_amount: item.nums * (product?.price || 0),
        order_status: 0
      };

      await orderAPI.add(order);

      // 更新商品库存
      const updatedProduct = {
        ...product,
        nums: product.nums - item.nums
      };
      await productAPI.edit(updatedProduct);

      // 从购物车中移除已购买商品
      await buycarAPI.del(item.id);
    }

    ElMessageBox.alert('订单提交成功', '成功', { type: 'success' });
    checkoutVisible.value = false;
    // 重新加载购物车数据
    await loadCartData();
    // 清空选择
    selectedProducts.value = [];
  } catch (error) {
    // 表单验证失败不显示错误弹窗
    if (error.name !== 'ValidationError') {
      console.error('提交订单失败:', error);
      ElMessageBox.alert('提交订单失败，请稍后重试', '错误', { type: 'error' });
    }
  }
};
</script>

<style scoped>
.mycart-container {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 40px);
}

.product-info {
  display: flex;
  align-items: center;
  justify-content: center;
}

.product-img {
  width: 50px;
  height: 50px;
  margin-right: 10px;
  object-fit: cover;
  border-radius: 4px;
}

.checkout-area {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.total-info {
  font-size: 16px;
  font-weight: bold;
  color: #f56c6c;
}
</style>